package com.qixiaobao.addminus.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.qixiaobao.addminus.domain.Addminus;
import com.qixiaobao.addminus.domain.dto.AddminusDTO;
import com.qixiaobao.addminus.domain.dto.AddminusPreservationNoTempDTO;
import com.qixiaobao.addminus.domain.vo.AddminusVo;
import com.qixiaobao.addminus.mapper.AddminusMapper;
import com.qixiaobao.addminus.service.IAddMinusService;
import com.qixiaobao.common.config.SupplyConfig;
import com.qixiaobao.common.core.domain.model.LoginUser;
import com.qixiaobao.common.core.rabbitmq.config.RabbitMqConfig;
import com.qixiaobao.common.core.rabbitmq.server.MsgSendServer;
import com.qixiaobao.common.exception.UtilException;
import com.qixiaobao.common.utils.MybatisBatchUtils;
import com.qixiaobao.common.utils.SecurityUtils;
import com.qixiaobao.common.utils.StringUtils;
import com.qixiaobao.common.utils.easyExcel.EasyExcelUtil;
import com.qixiaobao.common.utils.file.FileUtils;
import com.qixiaobao.common.utils.pdf.PdfWaterUtils;
import com.qixiaobao.common.utils.uuid.IdUtils;
import com.qixiaobao.insure.domain.MatchInsure;
import com.qixiaobao.system.domain.*;
import com.qixiaobao.system.domain.dto.PersonDTO;
import com.qixiaobao.insure.mapper.MatchInsureMapper;
import com.qixiaobao.common.utils.oss.OssUtil;
import com.qixiaobao.nondirect.invoice.domain.domain.*;
import com.qixiaobao.system.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @Description 增减员  业务层处理
 * @Author yangxm
 * @Date 2025/6/23 10:15
 */
@Slf4j
@Service
public class AddMinusServiceImpl implements IAddMinusService {

    @Autowired
    private AddminusMapper addminusMapper;
    @Autowired
    private MatchInsureMapper matchInsureMapper;
    @Autowired
    private SignCompanyMapper signCompanyMapper;
    @Autowired
    private SlaveUserMapper slaveUserMapper;
    @Autowired
    private DictMapper dictMapper;
    @Autowired
    private PersonMapper personMapper;
    @Autowired
    private MsgSendServer msgSendServer;


    /**
     * 批单上传文件后缀
     */
    private static final List<String> SUFFIX = Arrays.asList("pdf", "jpg", "jpeg", "png", "bmp");

    /**
     * 查询增减员列表
     *
     * @param addminusDTO 增减员信息
     * @return 增减员集合
     */
    @Override
    public List<Addminus> selectAddminusList(AddminusDTO addminusDTO) {
        long begin = System.currentTimeMillis();
        log.info("查询增减员列表开始：-------------------");
        List<Addminus> list = addminusMapper.selectAddminusList(addminusDTO);
        log.info("查询增减员列表sql结束：{}ms", System.currentTimeMillis() - begin);
        dictHandle(list);
        return list;
    }

    /**
     * @Description 查询增减员人数合计
     * @Author yangxm
     * @Date 2025/6/23 13:33
     * @param addminusDTO
     * @return
     */
    @Override
    public AddminusVo selectAddMinusPersonTotal(AddminusDTO addminusDTO) {
        return addminusMapper.selectAddMinusPersonTotal(addminusDTO);
    }

    /**
     * @Description 保险费总计
     * @Author yangxm
     * @Date 2025/6/23 15:08
     * @param addminusDTO
     * @return java.math.BigDecimal
     */
    @Override
    public BigDecimal selectCopeInsureFeeTotal(AddminusDTO addminusDTO) {
        return addminusMapper.selectCopeInsureFeeTotal(addminusDTO);
    }

    /**
     * @Description 导出
     * @Author yangxm
     * @Date 2025/6/23 15:08
     * @param addminusDTO
     * @param response
     */
    @Override
    public void export(AddminusDTO addminusDTO, HttpServletResponse response) {
        List<String> arrayHeaders = new ArrayList<>();
        arrayHeaders.add("序号");
        arrayHeaders.add("方案Id");
        arrayHeaders.add("ID号");
        arrayHeaders.add("订单编号");
        arrayHeaders.add("保全单号");
        arrayHeaders.add("保单号");
        arrayHeaders.add("供应商全称");
        arrayHeaders.add("所属供应商");
        arrayHeaders.add("供应商简称");
        arrayHeaders.add("匹配后供应商简称");
        arrayHeaders.add("所属公司");
        arrayHeaders.add("被保人");
        arrayHeaders.add("付款单位");
        arrayHeaders.add("客户名称");
        arrayHeaders.add("套餐名称");
        arrayHeaders.add("伤残比例");
        arrayHeaders.add("扩展24小时");
        arrayHeaders.add("投保周期");
        arrayHeaders.add("投保方式");
        arrayHeaders.add("职业类别");
        arrayHeaders.add("生效起期");
        arrayHeaders.add("生效止期");
        arrayHeaders.add("保险费(元/人)");
        arrayHeaders.add("投保人数");
        arrayHeaders.add("客服");
        arrayHeaders.add("保险费总计");
        arrayHeaders.add("手续费率");
        arrayHeaders.add("备注");
        arrayHeaders.add("推送时间");
        arrayHeaders.add("操作时间");
        arrayHeaders.add("批单状态");
        arrayHeaders.add("下载状态");
        arrayHeaders.add("保单结算状态");
        arrayHeaders.add("保单结算时间");
        arrayHeaders.add("回单金额");
        arrayHeaders.add("回单编号");
        arrayHeaders.add("付款日期");
        arrayHeaders.add("匹配时间");
        arrayHeaders.add("状态");
        //动态表头
        List<List<String>> headList=new ArrayList<>();
        List<String> head=null;
        for (String strHead:arrayHeaders) {
            head=new ArrayList<>();
            head.add(strHead);
            headList.add(head);
        }
        List<Addminus> addminusList = selectAddminusList(addminusDTO);
        String fileName = "增减员记录";
        //动态表头的数据
        List<List<Object>> datalist=new ArrayList<>();
        List<Object> obj=null;
        Addminus item;
        for (int i = 0; i < addminusList.size(); i++) {
            item = addminusList.get(i);
            obj = new ArrayList<>();
            obj.add(i + 1);
            obj.add(item.getCustomerMealId());
            obj.add(item.getId());
            obj.add(item.getQxbOrderNo());
            obj.add(item.getPreservationNo());
            obj.add(item.getInsureNo());
            obj.add(item.getSupplyName());
            obj.add(item.getBelongToSupply());
            obj.add(item.getSupplyShortName());
            obj.add(item.getToSupplyShortName());
            obj.add(item.getBelongCompanyName());
            obj.add(item.getInsurant());
            obj.add(item.getPayCompanyName());
            obj.add(item.getCustomerName());
            obj.add(item.getMealNameVal());
            obj.add(item.getMaimRatioVal());
            obj.add(item.getExtensionVal());
            obj.add(item.getInsurePeriodVal());
            obj.add(item.getInsureTypeVal());
            obj.add(item.getJobTypeVal());
            obj.add(Optional.ofNullable(item.getGurantBeginTime()).map(x-> DateFormatUtils.format(x, "yyyy/MM/dd HH:mm:ss")).orElse(""));
            obj.add(Optional.ofNullable(item.getGurantEndTime()).map(x-> DateFormatUtils.format(x, "yyyy/MM/dd HH:mm:ss")).orElse(""));
            obj.add(item.getCopeInsureFeePrice());
            obj.add(item.getInsurePerson());
            obj.add(item.getServiceName());
            obj.add(item.getCopeInsureFee());
            obj.add(item.getServiceRate());
            obj.add(item.getRemark());
            obj.add(Optional.ofNullable(item.getPushTime()).map(x-> DateFormatUtils.format(x, "yyyy/MM/dd HH:mm:ss")).orElse(""));
            obj.add(Optional.ofNullable(item.getServiceInsTime()).map(x-> DateFormatUtils.format(x, "yyyy/MM/dd HH:mm:ss")).orElse(""));
            if (StringUtils.isNotBlank(item.getServiceInsDec())){
                if (StringUtils.isNotBlank(item.getSupplyInsDec())){
                    obj.add("已生成");
                }else {
                    obj.add("未上传");
                }
            }else {
                obj.add("未生成");
            }
            obj.add(item.getEndorseDownStatus() == 1 ? "已下载" : "未下载");
            obj.add(item.getInsureFeeSettle());
            obj.add(Optional.ofNullable(item.getInsureFeeSettleTime()).map(x-> DateFormatUtils.format(x, "yyyy/MM/dd HH:mm:ss")).orElse(""));
            obj.add(item.getTransAmount());
            obj.add(item.getBillNum());
            obj.add(Optional.ofNullable(item.getTransDateTime()).map(x-> DateFormatUtils.format(x, "yyyy/MM/dd")).orElse(""));
            obj.add(Optional.ofNullable(item.getMatchTime()).map(x-> DateFormatUtils.format(x, "yyyy/MM/dd HH:mm:ss")).orElse(""));
            obj.add(item.getAbandonFlagVal());
            datalist.add(obj);
        }
        try {
            EasyExcelUtil.writeExcel(response, datalist, headList, fileName, fileName);
        } catch (IOException e) {
            log.error("{}导出异常：", fileName, e);
            throw new RuntimeException("导出失败：" + e.getMessage());
        }
    }

    /**
     * @Description 获取增减员人员详情
     * @Author yangxm
     * @Date 2025/6/23 15:26
     * @param personDTO
     * @return java.util.List<com.qixiaobao.nondirect.invoice.domain.domain.Person>
     */
    @Override
    public List<Person> personList(PersonDTO personDTO) {
        return personMapper.selectAddminusPersonList(personDTO);
    }

    /**
     * @Description 上传批单
     * @Author yangxm
     * @Date 2025/6/23 15:41
     * @param files
     * @param addminusId
     * @return java.lang.String
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String uploadEndorses(MultipartFile[] files, Long addminusId) {
        log.info("【AddMinusServiceImpl [uploadEndorses] 批单文件批量上传开始：");
        long begin = System.currentTimeMillis();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            throw new UtilException("登陆失效，请重新登陆！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        List<String> preservationNoList = new ArrayList<>();
        List<Addminus> updateAddminusList = new ArrayList<>();
        List<FileInfo> saveFileInfoList = new ArrayList<>();
        List<InsureLog> insureLogList = new ArrayList<>();
        Addminus updateAddminus = null;
        FileInfo saveFileInfo = null;
        InsureLog insureLog;
        MultipartFile file;
        //校验文件格式，获取每个文件的名称（保全单号）
        for (int i = 0; i < files.length; i++) {
            file = files[i];
            String fileName = file.getOriginalFilename();
            if (StringUtils.isBlank(fileName)){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、文件: " + fileName + " 无效。");
                continue;
            }
            if (!fileName.contains(".")){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、文件: " + fileName + " 无后缀。");
                continue;
            }
            String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            fileName = fileName.substring(0, fileName.lastIndexOf("."));
            //校验后缀是否是pdf
            if(StringUtils.isBlank(fileSuffix) || (!SUFFIX.contains(fileSuffix))) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、文件: " + fileName + " 格式错误，仅可上传 "+SUFFIX+" 文件。");
                continue;
            }
            //封装解析出来的保全单号
            preservationNoList.add(fileName);
        }
        //基础路径
        String basePath = SupplyConfig.getProfile() + IdUtils.fastSimpleUUID();
        //去重
        preservationNoList = preservationNoList.stream().distinct().collect(Collectors.toList());
        //根据解析出来的保全单号，查询增减员信息
        List<Addminus> addminusList = addminusMapper.selectAddminusByPreservationNoList(preservationNoList);
        if (StringUtils.isNotEmpty(addminusList)){
            Map<String, Addminus> addminusMap = addminusList.stream().collect(Collectors.toMap(Addminus::getPreservationNo, s -> s));
            //加水印后的文件路径
            String tarPdfPath;
            //另存未图片pdf的文件路径
            String imgPdfPath;
            //文件名称
            String fileName;
            Addminus addminus;
            String ossPath;
            String ossUrl;
            //保存
            for (int i = 0; i < files.length; i++) {
                file = files[i];
                fileName = file.getOriginalFilename();
                try {
                    fileName = fileName.substring(0, fileName.lastIndexOf("."));
                    log.info("【AddMinusServiceImpl [uploadEndorses] 批量上传批单文件，文件名：{}", fileName);
                    //根据保全编号查询增减员记录
                    addminus = addminusMap.get(fileName);
                    if(addminus == null){
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、文件: " + fileName + " 未查到增减人员记录。");
                        continue;
                    }else if (addminusId != null && !addminusId.equals(addminus.getId())){
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、文件: " + fileName + " 与系统保全单号不一致。");
                        continue;
                    }
                    if (StringUtils.isNotBlank(addminus.getSupplyInsDec())){
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、文件: " + fileName + " 批单文件已存在。");
                        continue;
                    }
                    //pdf加水印
                    if (file.getOriginalFilename().endsWith(".pdf")){
                        //加水印后的文件路径
                        tarPdfPath = basePath + "/water/" + file.getOriginalFilename();
                        //另存为图片pdf的文件路径
                        imgPdfPath = basePath + "/imgPdf/" + file.getOriginalFilename();
                        //添加水印
                        PdfWaterUtils.addWaterMark(file.getInputStream(), tarPdfPath, null, null);
                        //另存为图像pdf
                        PdfWaterUtils.saveAsImgPdf(tarPdfPath, imgPdfPath);
                        //加水印后的文件
                        file = new MockMultipartFile("file", file.getOriginalFilename(), "text/plain", Files.newInputStream(Paths.get(imgPdfPath)));
                    }
                    //将文件上传到oss系统
                    ossPath = FileUtils.getPath() + IdUtils.simpleUUID() + file.getOriginalFilename();
                    OssUtil.ins().uploadFile(ossPath, file.getInputStream());
                    //获取文件上传oss后的URL
                    ossUrl = OssUtil.ins().getFileUrl(ossPath);
                    //封装文件实体
                    saveFileInfo = new FileInfo();
                    saveFileInfo.setId(IdUtils.simpleUUID());
                    saveFileInfo.setContentType(file.getContentType());
                    saveFileInfo.setSize(file.getSize());
                    saveFileInfo.setPath(ossPath);
                    saveFileInfo.setUrl(ossUrl);
                    saveFileInfo.setType(file.getContentType().startsWith("image/") ? 1 : 0);
                    saveFileInfo.setOwner(IdUtils.simpleUUID());
                    //保存到list
                    saveFileInfoList.add(saveFileInfo);
                    //封装增减员实体
                    updateAddminus = new Addminus();
                    updateAddminus.setId(addminus.getId());
                    updateAddminus.setSupplyInsDec(ossUrl);
                    //同步给客户
                    updateAddminus.setCustomerInsDec(ossUrl);
                    //保存到list
                    updateAddminusList.add(updateAddminus);
                    //封装批单上传操作记录
                    insureLog = new InsureLog();
                    insureLog.setAddminusId(addminus.getId());
                    insureLog.setClient("2");
                    insureLog.setOperateType("6");
                    insureLog.setContent("批单上传");
                    insureLog.setFileUrlAfter(ossUrl);
                    insureLog.setCreateBy(loginUser.getUsername());
                    insureLogList.add(insureLog);

                    successNum++;
                    successMsg.append("<br/>" + successNum + "、文件: " + fileName + " 上传成功");
                }catch (Exception e){
                    failureNum++;
                    String msg = "<br/> 、文件： " + fileName + " 上传失败：";
                    failureMsg.append(msg + e.getMessage());
                    log.error("批单批量上传异常：", e);
                }
            }
        }
        //批量保存更新到数据库
        if (StringUtils.isNotEmpty(updateAddminusList)){
            MybatisBatchUtils.batchUpdateOrInsert(updateAddminusList, AddminusMapper.class, AddminusMapper::update);
        }
        if (StringUtils.isNotEmpty(saveFileInfoList)){
            MybatisBatchUtils.batchUpdateOrInsert(saveFileInfoList, FileInfoMapper.class, FileInfoMapper::insertFileInfo);
        }
        if (StringUtils.isNotEmpty(insureLogList)){
            MybatisBatchUtils.batchUpdateOrInsert(insureLogList, InsureLogMapper.class, InsureLogMapper::insertInsureLog);
        }
        //删除文件
        FileUtils.deleteDirectory(new File(basePath));
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，上传失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new RuntimeException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部上传成功！共 " + successNum + " 条，数据如下：");
        }

        log.info("【AddMinusServiceImpl [uploadEndorses] 批单批量上传完成，耗时：{}" , (System.currentTimeMillis() - begin));
        return successMsg.toString();
    }

    /**
     * @Description 定向下载模板  解析模板内容
     * @Author yangxm
     * @Date 2025/6/23 16:32
     * @param addminusPreservationNoTempDTOList
     * @return com.qixiaobao.addminus.domain.dto.AddminusPreservationNoTempDTO
     */
    @Override
    public AddminusPreservationNoTempDTO analysisEndorsesFile(List<AddminusPreservationNoTempDTO> addminusPreservationNoTempDTOList) {
        if (StringUtils.isEmpty(addminusPreservationNoTempDTOList)){
            throw new UtilException("数据不能为空");
        }
        //保全单号集合
        List<String> preservationNoList = addminusPreservationNoTempDTOList.stream().map(AddminusPreservationNoTempDTO::getPreservationNo).filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
        List<Addminus> addminusList = addminusMapper.selectAddminusByPreservationNoList(preservationNoList);
        if (StringUtils.isEmpty(addminusList)){
            throw new UtilException("未匹配到增减员数据");
        }
        //查询所有的增减员id
        List<Long> ids = addminusList.stream().map(Addminus::getId).collect(Collectors.toList());
        //查询所有的供应商简称
        List<String> supplyShortNameList = addminusList.stream().map(Addminus::getSupplyShortName).filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
        //根据保全单号集合查询批单信息
        Map<String, Addminus> addminusMap = addminusList.stream().collect(Collectors.toMap(Addminus::getPreservationNo, s -> s));

        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        String preservationNo;
        Addminus addminus;
        for (int i = 0; i < addminusList.size(); i++) {
            preservationNo = addminusList.get(i).getPreservationNo();
            if (StringUtils.isNotBlank(preservationNo)){
                //根据保全单号获取增减员信息
                addminus = addminusMap.get(addminusList.get(i).getPreservationNo());
                if (addminus == null){
                    log.error("【AddMinusServiceImpl】[analysisEndorsesFile] 增减员信息不存在：{}", preservationNo);
                    failureNum++;
                    String msg = "<br/>" + "保全单号： "+preservationNo+"，对应的增减员信息不存在！";
                    failureMsg.append(msg);
                    continue;
                }
                if (StringUtils.isBlank(addminus.getServiceInsDec())){
                    log.error("【AddMinusServiceImpl】[analysisEndorsesFile] 批单文件未生成：{}", preservationNo);
                    failureNum++;
                    String msg = "<br/>" + "保全单号： "+preservationNo+"，对应的批单文件未生成！";
                    failureMsg.append(msg);
                    continue;
                }
                if (!addminus.getSupplyShortName().equals(addminusList.get(i).getSupplyShortName())){
                    log.error("【AddMinusServiceImpl】[analysisEndorsesFile] 供应商简称错误：{}", preservationNo);
                    failureNum++;
                    String msg = "<br/>" + "保全单号： "+preservationNo+"，对应的供应商简称错误！";
                    failureMsg.append(msg);
                }
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，校验失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new UtilException(failureMsg.toString());
        }
        AddminusPreservationNoTempDTO dto = new AddminusPreservationNoTempDTO();
        dto.setAddminusIdList(ids);
        dto.setSupplyShortName(StringUtils.join(supplyShortNameList, ","));
        return dto;
    }

    /**
     * @Description 定向下载模板  批量下载批单
     * @Author yangxm
     * @Date 2025/6/23 16:58
     * @param addminusPreservationNoTempDTO
     */
    @Override
    public void downloadEndorsesByPreservationNoTemp(AddminusPreservationNoTempDTO addminusPreservationNoTempDTO) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null){
            throw new UtilException("用户未登录");
        }
        JSONObject message = new JSONObject();
        message.put("userId", loginUser.getId());
        message.put("client", "supply");
        message.put("ids", addminusPreservationNoTempDTO.getAddminusIdList());
        message.put("supplyShortName", addminusPreservationNoTempDTO.getSupplyShortName());
        msgSendServer.sendDirectByRoute(RabbitMqConfig.DIRECT_EXCHANGE, RabbitMqConfig.ENDORSES_ROUTING_KEY, message.toJSONString(), new CorrelationData(IdUtils.simpleUUID()));
    }

    /**
     * @Description 批量删除批单
     * @Author yangxm
     * @Date 2025/6/23 17:07
     * @param addminusIdArray
     * @return int
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteEndorses(Long[] addminusIdArray) {
        LoginUser user = SecurityUtils.getLoginUser();
        if (user == null){
            throw new IllegalArgumentException("登陆失效，请重新登陆！");
        }
        List<Addminus> addminusList = addminusMapper.selectAddminusByIds(addminusIdArray);
        if (StringUtils.isNotEmpty(addminusList)){
            Addminus addminus;
            InsureLog insureLog;
            List<InsureLog> insureLogList = new ArrayList<>();
            for (int i = 0; i < addminusList.size(); i++) {
                addminus = addminusList.get(i);
                insureLog = new InsureLog();
                insureLog.setAddminusId(addminus.getId());
                insureLog.setClient("2");
                insureLog.setOperateType("6");
                insureLog.setContent("批单删除");
                insureLog.setFileUrlBefore(addminus.getSupplyInsDec());
                insureLog.setCreateBy(user.getUsername());
                insureLogList.add(insureLog);
            }
            if (StringUtils.isNotEmpty(insureLogList)){
                MybatisBatchUtils.batchUpdateOrInsert(insureLogList, InsureLogMapper.class, InsureLogMapper::insertInsureLog);
            }
        }
        return addminusMapper.updateEndorsesByIds(addminusIdArray);
    }

    /**
     * @Description 字典数据处理
     * @Author yangxm
     * @Date 2025/6/23 13:33
     * @param list
     */
    private void dictHandle(List<Addminus> list) {

        if (StringUtils.isNotEmpty(list)){
            //获取所有的保单id
            List<Long> insureIdList = list.stream().map(Addminus::getInsureId).distinct().collect(Collectors.toList());
            //根据保单id，查询匹配后供应商简称
            List<MatchInsure> matchInsureList = matchInsureMapper.selectToSupplyShortNameList(insureIdList);
            Map<Long,String> toSupplyShortNameMap = null;
            if (StringUtils.isNotEmpty(matchInsureList)){
                toSupplyShortNameMap = matchInsureList.stream().collect(Collectors.toMap(MatchInsure::getFromInsureId, MatchInsure::getToSupplyShortName));
            }
            //账号信息
            Map<Long, String> usernameMap = slaveUserMapper.selectUsernameList().stream()
                    .collect(Collectors.toMap(SlaveUser::getId, SlaveUser::getUsername));
            //付款单位
            Map<Long, String> payCompanyNameMap = signCompanyMapper.selectSignCompanyNameList().stream()
                    .collect(Collectors.toMap(SignCompany::getId, SignCompany::getCompanyName));

            List<Dict> dictList = dictMapper.selectDictList();
            Map<String, Map<String, String>> dictMap = new ConcurrentHashMap<>();
            if (StringUtils.isNotEmpty(dictList)) {
                dictMap = dictList.stream()
                        .filter(c -> c.getVal() != null)
                        .collect(Collectors.groupingBy(Dict::getType, Collectors.toMap(Dict::getK, Dict::getVal)));
            }
            Map<String, String> mealNameMap = dictMap.getOrDefault("mealname", Collections.emptyMap());
            Map<String, String> maimRatioMap = dictMap.getOrDefault("maimRatio", Collections.emptyMap());
            Map<String, String> insureperiodMap = dictMap.getOrDefault("insureperiod", Collections.emptyMap());
            Map<String, String> insuretypeMap = dictMap.getOrDefault("insuretype", Collections.emptyMap());
            Map<String, String> jobtypeMap = dictMap.getOrDefault("jobtype", Collections.emptyMap());
            Map<String, String> extensionMap = dictMap.getOrDefault("extension", Collections.emptyMap());

            Addminus addminus = null;
            for (int i = 0; i < list.size(); i++) {
                addminus = list.get(i);
                addminus.setPayCompanyName((StringUtils.equals("0", addminus.getInsureType()) || StringUtils.equals("1", addminus.getInsureType()))
                        ? addminus.getCustomerName() : payCompanyNameMap.getOrDefault(addminus.getPayCompanyId(), ""));
                addminus.setMealNameVal(mealNameMap.get(addminus.getMealName()));
                addminus.setMaimRatioVal(maimRatioMap.get(addminus.getMaimRatio()));
                addminus.setInsurePeriodVal(insureperiodMap.get(addminus.getInsurePeriod()));
                addminus.setInsureTypeVal(insuretypeMap.get(addminus.getInsureType()));
                addminus.setJobTypeVal(jobtypeMap.get(addminus.getJobType()));
                addminus.setExtensionVal(extensionMap.get(addminus.getExtension()));
                addminus.setAbandonFlagVal(addminus.getAbandonFlag() == 1 ? "退保减员" : "");
                addminus.setServiceName(usernameMap.getOrDefault(addminus.getServiceId(), ""));
                if (toSupplyShortNameMap != null) {
                    addminus.setToSupplyShortName(toSupplyShortNameMap.getOrDefault(addminus.getInsureId(), ""));
                }
                addminus.setEndorseStatusVal("未生成");
                if (StringUtils.isNotBlank(addminus.getServiceInsDec())){
                    if (StringUtils.isNotBlank(addminus.getSupplyInsDec())){
                        addminus.setEndorseStatusVal("已生成");
                    }else {
                        addminus.setEndorseStatusVal("未上传");
                    }
                }
                addminus.setInsurePerson("增员:" + addminus.getAddNum() + ";减员:" + addminus.getMinusNum());
            }
        }
    }
}
